import {back} from '../../../utils/util';
import {getDate, convertDate, getTime} from '../../../utils/date';
import {creactPlanApi, finishPlanApi} from '../../../api/app';

const app = getApp ();
Page ({
  /**
   * 页面的初始数据
   */
  data: {
    readChecked: true, // 是否隐藏阅读计划
    motionChecked: true, // 是否隐藏运动计划
    maxHour: 12, // 阅读时长小时最高值
    maxMin: 59, // 阅读时长分钟最高值
    // 计划设置
    startDate: '', // 开始日期
    endDate: '', // 结束时间
    daySelect: ['工作', '学习', '娱乐', '生活', '其他'], // 类型
    readTimeValue: [2, 30],
    motionTimeValue: [1, 15],
    motionDayValue: 0, // 运动打卡天数
    planName: '', // 计划名称
    content: '', // 内容
    startTime: '12:00',
    endTime: '13:00',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // tempDate.setDate(tempDate.getDate() + day);
    const startDate = getDate (new Date (), '-');
    const endDate = convertDate (startDate, 1, '-');
    const data = options.data ? JSON.parse (options.data) : '';
    if (data) {
      this.setData ({
        planName: data.title,
        content: data.content,
        motionDayValue: data.planType - 1,
        title: '编辑计划',
        startDate: getDate (new Date (data.planStartTime), '-'),
        startTime: getTime (new Date (data.planStartTime)),
        endDate: getDate (new Date (data.planEndTime), '-'),
        endTime: getTime (new Date (data.planEndTime)),
        isEdit: true,
        id: data.id,
      });
      console.log(getTime (new Date (data.planEndTime)))
    } else {
      this.setData ({
        startDate,
        endDate,
        motionDayValue: options.planType - 1 >= 0 ? options.planType - 1 : 0,
        title: '创建计划',
        isEdit: false,
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  onInput (event) {
    this.setData ({
      currentDate: event.detail,
    });
  },
  // 选择运动天数
  selectType (e) {
    const motionDayValue = Number (e.detail.value);
    this.setData ({
      motionDayValue,
    });
  },

  // 选择日期
  selectStartDate (e) {
    console.log (e);
    const startDate = new Date (e.detail.value).getTime ();
    const endDate = new Date (this.data.endDate).getTime ();
    // 判断是否合法
    if (startDate > endDate) {
      app.toast (`开始日期不能晚于结束日期`);
      return;
    }
    this.setData ({
      startDate: getDate (new Date (startDate), '-'),
    });
  },
  // 选择开始时间
  selectStartTime (e) {
    const startDate = new Date (
      this.data.startDate + ' ' + e.detail.value
    ).getTime ();
    const endDate = new Date (
      this.data.endDate + ' ' + this.data.endTime
    ).getTime ();
    // 判断是否合法
    if (startDate > endDate) {
      app.toast (`开始日期不能晚于结束日期`);
      return;
    }
    this.setData ({
      startTime: e.detail.value,
    });
  },
  // 选择开始时间
  selectEndTime (e) {
    const startDate = new Date (
      this.data.startDate + ' ' + this.data.startTime
    ).getTime ();
    const endDate = new Date (
      this.data.endDate + ' ' + e.detail.value
    ).getTime ();
    // 判断是否合法
    if (startDate > endDate) {
      app.toast (`开始日期不能晚于结束日期`);
      return;
    }
    this.setData ({
      endTime: e.detail.value,
    });
  },
  // 选择日期
  selectEndDate (e) {
    const startDate = new Date (this.data.startDate).getTime ();
    const endDate = new Date (e.detail.value).getTime ();
    // 判断是否合法
    if (endDate < startDate) {
      app.toast (`结束日期不能早于开始日期`);
      return;
    }
    this.setData ({
      endDate: getDate (new Date (endDate), '-'),
    });
  },
  // 返回事件
  backHandle () {
    wx.showModal ({
      title: '温馨提示',
      content: '是否放弃创建该计划？',
      success (res) {
        if (res.confirm) {
          back ();
        }
      },
    });
  },
  // 监听readCheckedChange
  readCheckedChange (e) {
    console.log (e.detail.value);
    this.setData ({
      readChecked: e.detail.value,
    });
  },
  motionCheckedChange (e) {
    console.log (e.detail.value);
    this.setData ({
      motionChecked: e.detail.value,
    });
  },
  // 提交
  submit () {
    if (this.data.isEdit) {
      this.editPlan ();
    } else {
      if (this.data.motionChecked) {
        wx.requestSubscribeMessage ({
          tmplIds: ['Q0ptzgVtY5hnt2BoYZrHw7IROu8rBjO62SeSJ23R7-Q'],
          success: async res => {
            console.log (res);
            this.createPlan ();
          },
          fail (err) {
            console.log (err);
          },
        });
      } else {
        this.createPlan ();
      }
    }
  },
  // 编辑
  async editPlan () {
    try {
      const res = await finishPlanApi ({
        id: this.data.id,
        title: this.data.planName,
        content: this.data.content,
        planStartTime: this.data.startDate + ' ' + this.data.startTime,
        planEndTime: this.data.endDate + ' ' + this.data.endTime,
        planType: this.data.motionDayValue + 1,
      });
      if (res.code == 200) {
        wx.showToast ({
          title: '编辑成功！',
          icon: 'none',
        });
        setTimeout (() => {
          wx.redirectTo ({
            url: '/subPages/clockin/clockin-plan/index',
          });
        }, 1500);
      } else {
        wx.showToast ({
          title: res.msg,
          icon: 'none',
        });
      }
    } catch (error) {
      console.log (error);
    }
  },
  // 创建
  async createPlan () {
    try {
      const res = await creactPlanApi ({
        title: this.data.planName,
        content: this.data.content,
        planStartTime: this.data.startDate + ' ' + this.data.startTime,
        planEndTime: this.data.endDate + ' ' + this.data.endTime,
        planType: this.data.motionDayValue + 1,
      });
      if (res.code == 200) {
        wx.showToast ({
          title: '创建成功！',
          icon: 'none',
        });
        setTimeout (() => {
          wx.redirectTo ({
            url: '/subPages/clockin/clockin-plan/index',
          });
        }, 1500);
      } else {
        wx.showToast ({
          title: res.msg,
          icon: 'none',
        });
      }
    } catch (error) {
      console.log (error);
    }
  },
  // 跳转
  toSelectBook () {
    wx.navigateTo ({
      url: '/appPages/clockin/select-book/index?from=createPlan',
    });
  },
});
